﻿#region Header

/*
    This file is part of nDoctor Light

    NDoctor is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    NDoctor is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with NDoctor.  If not, see <http://www.gnu.org/licenses/>.
*/

#endregion Header

namespace Probel.Ldoc.Shell.Configuration
{
    using System;
    using System.Configuration;
    using System.IO;
    using System.Reflection;

    using Nini.Config;

    public class ConfigFile : IConfigFile
    {
        #region Fields

        private const string CONFIG_FILE = @"%appdata%\Probel\nDoctor Light\Configuration.xml";

        private readonly IConfigSource Source;

        #endregion Fields

        #region Constructors

        private ConfigFile()
        {
            Source = new XmlConfigSource(GetConfigurationFilePath());
        }

        #endregion Constructors

        #region Properties

        public string Database
        {
            get { return Source.Configs["Configuration"].GetString("Database"); }
        }

        #endregion Properties

        #region Methods

        public static IConfigFile GetConfiguration()
        {
            var path = GetConfigurationFilePath();
            if (!File.Exists(path))
            {
                var assembly = Assembly.GetExecutingAssembly();
                var resourceName = "Probel.Ldoc.Shell.Configuration.Configuration.xml";

                using (Stream stream = assembly.GetManifestResourceStream(resourceName))
                using (StreamReader reader = new StreamReader(stream))
                {
                    string result = reader.ReadToEnd();

                    File.WriteAllText(path, result);
                }
            }
            return new ConfigFile();
        }

        private static string GetConfigurationFilePath()
        {
            var path = Environment.ExpandEnvironmentVariables(CONFIG_FILE);
            return path;
        }

        #endregion Methods
    }
}